import hashlib
import json
import re

from flask import Blueprint, make_response, session, request, url_for

from app.config.config import config
from app.settings import env
from common import response_message
from common.email_utils import gen_email_code, send_email
from common.redisdb import redis_connect
from common.utils import ImageCode
from model.user import User

redis_user = Blueprint('redis_user', __name__)


redis_client = redis_connect()

# @user.route('/aa')
# def get_one():
#     user = User()
#     result = user.get_one()
#     print(result)
#     print(result.username)
#     return 'ok'


@redis_user.route('/redis/vcode')
def vcode():
    code, bstring = ImageCode().get_code()
    response = make_response(bstring)
    response.headers['Content-Type'] = 'image/jpeg'
    session['vcode'] = code.lower()
    print(code.lower())
    return response


@redis_user.route('/redis/ecode', methods=['post'])
def email_code():
    # email = request.form.get('email')
    email = json.loads(request.data).get('email')
    print(email)
    if not re.match('\d+@\w+\.\w+', email):
        return response_message.UserMessage.other('无效的邮箱')

    code = gen_email_code()
    try:
        send_email(email, code)
        # session['ecode'] = code.lower()
        email_vcode = 'email:' + email
        redis_client.set(email_vcode, code.lower())
        redis_client.expire(email_vcode, 60)
        return response_message.UserMessage.success('邮件发送成功')
    except Exception as e:
        print(e)
        return response_message.UserMessage.error('邮件发送失败')


@redis_user.route('/redis/reg', methods=['POST'])
def register():
    request_data = json.loads(request.data)
    username = request_data.get('username')
    password = request_data.get('password')
    second_password = request_data.get('second_password')
    ecode = request_data.get('ecode')

    redis_ecode = redis_client.get('email:' + username)

    if ecode.lower() != redis_ecode:
        return response_message.UserMessage.error('邮箱验证码错误')

    if not re.match('\d+@\w+\.\w+', username):
        return response_message.UserMessage.other('无效的邮箱')

    if len(password) < 6:
        return response_message.UserMessage.error('密码不合法')

    if password != second_password:
        return response_message.UserMessage.error('两次密码不一致')

    user = User()
    if len(user.find_by_username(username=username)) > 0:
        return response_message.UserMessage.error('用户名已存在')

    password = hashlib.md5(password.encode()).hexdigest()
    result = user.do_register(username, password)
    return response_message.UserMessage.success('注册成功')



@redis_user.route('/redis/login', methods=['POST'])
def login():
    request_data = json.loads(request.data)
    username = request_data.get('username')
    password = request_data.get('password')
    vcode = request_data.get('vcode')
    # if vcode.lower() != session['vcode']:
    #     return response_message.UserMessage.error('验证码输入错误')

    password = hashlib.md5(password.encode()).hexdigest()

    result = redis_client.get('user:' + username)

    if result is None:
        user = User()
        result = user.find_by_username(username=username)
        if len(result) == 1 and result[0].password == password:
            session['is_login'] = 'true'
            session['user_id'] = result[0].user_id
            session['username'] = username
            session['nickname'] = result[0].nickname
            session['picture'] = config[env].user_header_image_path + result[0].picture

            response = make_response(response_message.UserMessage.success('登录成功'))
            response.set_cookie('username', username)

            return response
        else:
            return response_message.UserMessage.error('用户名或者密码错误')
    else:
        result = eval(result)
        if result.get('password') == password:
            response = make_response(response_message.UserMessage.success('登录成功'))
            return response
        else:
            return response_message.UserMessage.error('用户名或者密码错误')



@redis_user.route('/redis/login2', methods=['POST'])
def login2():
    request_data = json.loads(request.data)
    username = request_data.get('username')
    password = request_data.get('password')

    password = hashlib.md5(password.encode()).hexdigest()

    redis_password = redis_client.hget('hash_user:' + username, username)
    if redis_password == password:
        response = make_response(response_message.UserMessage.success('登录成功'))
        return response
    else:
        return response_message.UserMessage.error('用户名或者密码错误')

